﻿namespace WebMVC.Controllers
{
    using System;
    using System.Diagnostics;
    using System.Net.Http;
    using System.Threading.Tasks;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.Extensions.Logging;
    using WebMVC.Models;
    using WebMVC.Services;
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;
        private readonly IConditionService CondSvc;

        public HomeController(ILogger<HomeController> logger, IConditionService condSvc)
        {
            _logger = logger;
            CondSvc = condSvc;
        }

        public async Task<IActionResult> CheckCondition()
        {
            var result = await CondSvc.GetCondition().ConfigureAwait(true);
            return Ok(new
            {
                Message = result
            });
        }

        public async Task<IActionResult> Index()
        {
            string condition = await GetDrivingCondition();
            ViewBag.DrivingCondition = condition;

            return View();
        }

        public IActionResult Privacy()
        {
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }


        private const string driveConditionUrl = "http://localhost:9080/home/condition";
        private static async Task<string> GetDrivingCondition()
        {
            try
            {
                //// REST call
                HttpClient client = new HttpClient();
                HttpResponseMessage response = await client.GetAsync(driveConditionUrl);
                string responseString = await response.Content.ReadAsStringAsync();

                return responseString;
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"[ERROR] Failed to get driving conditions. URL: {driveConditionUrl}, Error: {ex.Message}");
                return null;
            }
        }
    }
}
